package fr.free.hd.servers.android.geonaute.connector;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.isobar.isohealth.models.HeartRate;
import com.isobar.isohealth.models.NewFitnessActivity;
import com.isobar.isohealth.models.WGS84;

import fr.free.hd.servers.android.geonaute.connector.model.Track;
import fr.free.hd.servers.android.geonaute.connector.model.TrackPoint;

public final class TrackConverter {

	public static NewFitnessActivity convertTrackToRunKeeper(Track track)
	{
		NewFitnessActivity activity = new NewFitnessActivity();
		
		activity.setAverage_heart_rate(track.AvgHeartBeat);
		activity.setDuration((double) (track.Duration_h*60*60 + track.Duration_m*60 + track.Duration_s));
		activity.setHeart_rate(convertHeartRate(track));
		activity.setNotes(null);
		activity.setPath(convertGPS(track));
		activity.setPost_to_facebook(false);
		activity.setPost_to_twitter(false);
		activity.setStart_time(ToDate(track));
		activity.setTotal_calories((double)track.Calories);
		activity.setTotal_distance((double)track.Distance);
		activity.setType("Running");		
		
		return activity;
	}
	
	private static  String ToDate(Track track)
	{
		Date time = new Date(track.Year, track.Month, track.Day, track.Hour, track.Min, track.Sec);
		SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
		return format.format(time);
	}
	
	private  static HeartRate[] convertHeartRate(Track track)
	{
		ArrayList<HeartRate> ht = new ArrayList<HeartRate>();
		for (int i = 0; i < track.tps.size(); i++) {
			HeartRate heartRate = new HeartRate();
			TrackPoint point = track.tps.get(i);	
			heartRate.setHeart_rate(point.HeartRate);
			//Let's consider taht we do it every second which is the default
			heartRate.setTimestamp((double)i);
			ht.add(heartRate);
		}
		
		return (HeartRate[]) ht.toArray(new HeartRate[track.tps.size()]);
	 
	}
	
	private static  WGS84[] convertGPS(Track track)
	{
		ArrayList<WGS84> ht = new ArrayList<WGS84>();
		for (int i = 0; i < track.tps.size(); i++) {
			WGS84 heartRate = new WGS84();
			TrackPoint point = track.tps.get(i);	
			heartRate.setAltitude((double)point.Alt);
			heartRate.setLatitude((double)point.Lat);
			heartRate.setLongitude((double)point.Lon);
			//One of the following values: start, end, gps, pause, resume, manual
			heartRate.setType("gps");
			//Let's consider taht we do it every second which is the default
			heartRate.setTimestamp((double)i);
			ht.add(heartRate);
		}
		
		return (WGS84[]) ht.toArray(new WGS84[track.tps.size()]);
	 
	}
}
